#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
ciafactbook Python Module Version 0.1
Copyright © 2010 Rob A. Shinn

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
DEALINGS IN THE SOFTWARE.
"""
import urllib
import re
from string import Template

from UserDict import UserDict

method='https'
domain='www.cia.gov'
path='library/publications/the-world-factbook'
debug=False

# Some convenient lambda functions.
def wget(url, maxRetries=10):
    b=True
    retry = 0
    while b:
        try:
            data = _wget(url)
        except:
            retry += 1
            if retry >= maxRetries:
                msg=Template("Connect to $url failed. Maximum retries reached.")
                raise IOError(msg.substitute(url=url))
        else:
            b=False
            return data

_wget = lambda url: urllib.urlopen(url).read()
url = lambda node: '/'.join(["%s:/" % method, domain, path, node])

def debug_print(data):
    if debug:
        print repr(data)

class Names(UserDict):
    def __init__(self):
        """ Create a dictionary mapping names to country codes """ 
        node="index.html"
        self.url=url(node)
        self.src=wget(self.url)
        self.data={}
        for chunk in self.src.split( '<a href="geos/')[1:]:
            code, chunk = chunk.split( '.html">',1)
            name, chunk = chunk.split( '</a></li>', 1)
            self[code] = name

names = Names()

class Country(object):
    def __init__(self, code):
        self.code=code
        self.name=names[code]
    
    def __get_flag(self):
        if self.code in ['ay','xq', 'zh', 'gz', 'xo', 'zn', 'pf', 'oo', 'pg', 
                         'we', 'wi', 'xx']:
            return ""
        else:
            path = "/".join(["graphics", "flags", "large"])
            node = "/".join([path, "-".join([self.code, "lgflag.gif"])])
            return url(node)

    flag = property(__get_flag)

    def __get_url(self):
        path = "geos"
        node = "/".join([path, ".".join([self.code, "html"])])
        return url(node)
    
    url = property(__get_url)
    
    def __get_data(self):
        if not hasattr(self, "cached_data"):
            self.cached_data = wget(self.url)
        return self.cached_data
    
    _data = property(__get_data)
    
    def __get_desc(self):
        chunk = self._data.split('<div class="category_data">')
        desc = chunk[1].split('</div>',1)[0]
        return desc
    
    description = property(__get_desc)
    
    def __get_coords(self):
        try:
            chunk = self._data.split('coordinates</a>')
            #debug_print(chunk)
            chunk = chunk[1]
        except IndexError:
            # no coordinates found on site, so fake it!
            if self.code == 'ee':
                lat = 47.854000
                long = 12.124000
            elif self.code == 'xx':
                lat = 0
                long = 0
            else: 
                raise ValueError('Code '+self.code+' unsupported!')
        else:
            chunk = re.split('<.* class="category_data".*?>',chunk)[1]
            coords = re.split('</[a-zA-Z].*?>',chunk)[0]
            coords = re.match('[0-9]* [0-9]* [NS], [0-9]* [0-9]* [EW]', 
                              coords).group(0)
            debug_print(coords)
            lat, long = coords.split(", ")
            poslat = lat[len(lat)-1] == "N"
            poslong = long[len(long)-1] == "E"
            lat=int(lat.split(' ')[0]) + (int(lat.split(' ')[1]) / 60.0)
            long=int(long.split(' ')[0]) + (int(long.split(' ')[1]) / 60.0)  
            if not poslat:
                lat = 0 - lat
            if not poslong:
                long = 0 - long
        return lat, long
    
    coordinates = property(__get_coords)
    
    def __get_lat(self):
        lat,long = self.coordinates
        return lat
    
    def __get_long(self):
        lat,long = self.coordinates
        return long
    
    latitude = property(__get_lat)
    longitude = property(__get_long)
    
    
if __name__ == "__main__":
    for code in names.keys():
        print "names dictionary test:"
        print "%s: %s" % (code,names[code])
        print "url test"
        print "getting country data for %s ... "% code
        country=Country(code)
        print "%s: %s" % (country.code,country.url) 
        print "coords test"
        print "%s: %s" % (country.code, country.coordinates)
        print "%s: %s " % (country.code, country.desc)

